package com.dy.drp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dy.drp.dto.BuyListDto;
import com.dy.drp.dto.SaleShortTimeDto;
import com.dy.drp.entity.*;
import com.dy.drp.mapper.*;
import com.dy.drp.service.ISaleshorttimeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.drp.vo.SaleinfoVo;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.A;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dy
 * @since 2022-04-02
 */
@Service
public class SaleshorttimeServiceImpl extends ServiceImpl<SaleshorttimeMapper, Saleshorttime> implements ISaleshorttimeService {
    @Autowired
    private CargoMapper cargoMapper;
    @Autowired
    private SaleinfoMapper saleinfoMapper;
    @Autowired
    private SalelistMapper salelistMapper;
    @Autowired
    private SaleshorttimeMapper saleshorttimeMapper;
    @Autowired
    private ClientMapper clientMapper;

    @Override
    public boolean saleFromFactory(SaleinfoVo saleinfoVo) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        saleinfoVo.setSaleTime(df.format(new Date()));
        QueryWrapper<Client> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("client_name",saleinfoVo.getClientName());
        Client client = clientMapper.selectOne(queryWrapper);
        saleinfoVo.setClientId(client.getClientId());
        saleinfoMapper.insertOneSaleInfo(saleinfoVo);
        List<Saleshorttime> saleshorttimes = saleshorttimeMapper.selectList(null);
        saleshorttimes.stream().forEach(r->{
            Cargo cargo = cargoMapper.selectById(r.getCargoId());
            cargo.setCargoNumber(cargo.getCargoNumber()-r.getSaleshortNumber());
            QueryWrapper<Cargo> wrapper = new QueryWrapper<>();
            wrapper.eq("cargo_id",r.getCargoId());
            cargoMapper.update(cargo,wrapper);
            Salelist salelist = new Salelist(null,r.getCargoId(),saleinfoVo.getSaleId(),r.getSaleshortNumber());
            salelistMapper.insert(salelist);
        });
        Integer truncate = saleshorttimeMapper.truncate();
        if (truncate == 0){
            return true;
        }
        return false;
    }

    @Override
    public List<SaleShortTimeDto> selectAllSaleShortTime() {
        return saleshorttimeMapper.selectAllSaleShortTime();
    }

}
